<template>
  <div class="add-shop-wrapper">
    <div class="add-shop-card">
      <h2>修改商品</h2>
      <form @submit.prevent="submitForm" class="shop-form">
        <div class="form-group">
          <label for="foodId">商品ID *</label>
          <input
              type="number"
              id="foodId"
              v-model.number="foodId"
              placeholder="请输入商品id"
              required
          />
        </div>

        <div class="form-group">
          <label for="foodName">商品名称</label>
          <input
              type="text"
              id="foodName"
              v-model="formData.foodName"
              placeholder="请输入商品名称"
          />
        </div>

        <div class="form-group">
          <label for="foodExplain">商品说明</label>
          <input
              type="text"
              id="foodExplain"
              v-model="formData.foodExplain"
              placeholder="请输入商品说明"
          />
        </div>

        <div class="form-group">
          <label for="foodImg">商品图片链接</label>
          <input
              type="url"
              id="foodImg"
              v-model="formData.foodImg"
              placeholder="请输入图片链接"
          />
        </div>

        <div class="form-group">
          <label for="foodPrice">商品价格（元）</label>
          <input
              type="number"
              step="0.01"
              id="foodPrice"
              v-model.number="formData.foodPrice"
              placeholder="请输入商品价格"
          />
        </div>

        <div class="form-group">
          <label for="remarks">备注</label>
          <input
              type="text"
              id="remarks"
              v-model="formData.remarks"
              placeholder="请输入商品备注"
          />
        </div>

        <!-- 提交与取消按钮 -->
        <div class="button-group">
          <button type="button" class="cancel-btn" @click="goBack">取消</button>
          <button type="submit" class="submit-btn" :disabled="isSubmitting">
            {{ isSubmitting ? '提交中...' : '修改商品' }}
          </button>
        </div>

        <!-- 消息提示 -->
        <p v-if="message" :class="['message', message.type]">{{ message.text }}</p>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();

// 商品ID
const foodId = ref(null)

// 表单数据对象
const formData = ref({
  foodName: '',
  foodExplain: '',
  foodImg: '',
  foodPrice: null,
  remarks: ''
});

// 提交状态
const isSubmitting = ref(false);

// 消息提示
const message = ref(null);

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 提交表单
const submitForm = async () => {
  message.value = null;

  // 必填校验
  if (foodId.value === null || foodId.value <= 0) {
    message.value = { type: 'error', text: '请正确输入商品id！' };
    return;
  }

  const hasAnyFieldFilled =
      formData.value.foodName?.trim() ||
      formData.value.foodExplain?.trim() ||
      formData.value.foodImg?.trim() ||
      formData.value.foodPrice !== null ||
      formData.value.remarks?.trim()

  if (!hasAnyFieldFilled) {
    message.value = { type: 'error', text: '请至少填写一个字段！' }
    return
  }

  const hasAllFieldFilled =
      formData.value.foodName?.trim() &&
      formData.value.foodExplain?.trim() &&
      formData.value.foodImg?.trim() &&
      formData.value.foodPrice !== null &&
      formData.value.remarks?.trim()

  try {
    isSubmitting.value = true;

    // 获取 JWT Token
    const token = sessionStorage.getItem('jwt');
    if (!token) {
      message.value = { type: 'error', text: '用户未登录！' };
      return;
    }

    if (hasAllFieldFilled) {
      const payload = {
        foodName: formData.value.foodName,
        foodExplain: formData.value.foodExplain,
        foodImg: formData.value.foodImg,
        foodPrice: formData.value.foodPrice,
        remarks: formData.value.remarks,
      }

      const response = await axios.put(`/foods/${foodId.value}`, payload, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token.slice(1, -1)}`,
        },
      })

      if (response.status === 200 || response.status === 201) {
        message.value = { type: 'success', text: '商品信息更新成功（完全更新）！' }
        setTimeout(() => {
          router.go(-1)
        }, 3000)
      }
    } else {
      const updates = {}

      if (formData.value.foodName?.trim()) updates.foodName = formData.value.foodName
      if (formData.value.foodExplain?.trim()) updates.foodExplain = formData.value.foodExplain
      if (formData.value.foodImg?.trim()) updates.foodImg = formData.value.foodImg
      if (formData.value.foodPrice !== null) updates.foodPrice = formData.value.foodPrice
      if (formData.value.remarks?.trim()) updates.remarks = formData.value.remarks

      const response = await axios.patch(`/foods/${foodId.value}`, updates, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token.slice(1, -1)}`,
        },
      })

      if (response.status === 200 || response.status === 201) {
        message.value = { type: 'success', text: '商品信息更新成功（部分更新）！' }
        setTimeout(() => {
          router.go(-1)
        }, 3000)
      }
    }
  } catch (err) {
    console.error('修改商品失败:', err);
    if (err.response) {
      // 服务器返回错误信息
      const errorMsg = err.response.data?.message || '修改商品失败';
      message.value = { type: 'error', text: errorMsg };
    } else if (err.request) {
      message.value = { type: 'error', text: '网络错误，请检查连接！' };
    } else {
      message.value = { type: 'error', text: '修改商品失败，请重试！' };
    }
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
/* 页面容器，垂直水平居中 */
.add-shop-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

/* 卡片容器 */
.add-shop-card {
  width: 100%;
  max-width: 600px;
  padding: 30px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 24px;
}

.shop-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

label {
  font-weight: bold;
  color: #555;
}

input {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus {
  outline: none;
  border-color: #007bff;
}

/* 按钮样式 */
.button-group {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.submit-btn {
  flex: 1;
  padding: 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover:not(:disabled) {
  background-color: #0056b3;
}

.submit-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.cancel-btn {
  flex: 1;
  padding: 12px;
  background-color: #f0f0f0;
  color: #333;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}

/* 消息提示样式 */
.message {
  margin-top: 15px;
  padding: 12px;
  border-radius: 6px;
  text-align: center;
  font-size: 14px;
}

.message.success {
  background-color: #e6ffed;
  color: #1a7324;
  border: 1px solid #b7eb8f;
}

.message.error {
  background-color: #ffebee;
  color: #c62828;
  border: 1px solid #ffa4a4;
}
</style>